<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="预约时间" prop="appointmentTime">
        <el-date-picker clearable
          v-model="queryParams.appointmentTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择预约时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['appointment:appointment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['appointment:appointment:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['appointment:appointment:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['appointment:appointment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appointmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="预约唯一标识符" align="center" prop="id" />
      <el-table-column label="预约时间" align="center" prop="appointmentTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.appointmentTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会员" align="center" prop="memberName" />
      <el-table-column label="员工" align="center" prop="employeeName" />
      <el-table-column label="预估收益" align="center" prop="estimatedProfit" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="hxq_appointment_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="notes" />
      <el-table-column label="提醒客户" align="center" prop="reminderTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reminderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目" align="center" prop="projectId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['appointment:appointment:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['appointment:appointment:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预约管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="appointmentRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker clearable
            v-model="form.appointmentTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="会员" prop="memberId">
          <el-input v-model="form.memberId" placeholder="请输入会员" />
        </el-form-item>
        <el-form-item label="员工" prop="employeeId">
          <el-input v-model="form.employeeId" placeholder="请输入员工" />
        </el-form-item>
        <el-form-item label="预估收益" prop="estimatedProfit">
          <el-input v-model="form.estimatedProfit" placeholder="请输入预估收益" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择预约状态">
            <el-option
              v-for="dict in hxq_appointment_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="form.notes" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="提醒客户" prop="reminderTime">
          <el-date-picker clearable
            v-model="form.reminderTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择提醒客户">
          </el-date-picker>
        </el-form-item>
<!--       
        <el-form-item label="项目" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入项目" />
        </el-form-item> -->
        <!-- 以下代码需要居中 -->
        <el-divider content-position="center">项目</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddAppointmentProject">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteAppointmentProject">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="appointmentProjectList" :row-class-name="rowAppointmentProjectIndex" @selection-change="handleAppointmentProjectSelectionChange" ref="appointmentProject">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="项目id
            " prop="projectId" width="150">
            <template #default="scope">
              <!-- <el-input v-model="scope.row.projectId" placeholder="请输入项目id -->

              
          <el-select
            v-model="form.projectId"
            filterable
            clearable
            remote
            :remote-method="getProjectList"
            :loading="loadingProjects"
            placeholder="请选择项目"
          >
            <el-option
              v-for="item in projectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
            </template>
            
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Appointment">
import { listAppointment, getAppointment, delAppointment, addAppointment, updateAppointment } from "@/api/appointment/appointment";
import { listHxqProject } from "@/api/hxqProject/hxqProject";
const { proxy } = getCurrentInstance();
const { hxq_appointment_status } = proxy.useDict('hxq_appointment_status');

const appointmentList = ref([]);
const appointmentProjectList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedAppointmentProject = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");




// 添加项目列表相关状态
const projectOptions = ref([]);
const loadingProjects = ref(false);

// 获取项目列表
function getProjectList() {
  loadingProjects.value = true;
  listHxqProject().then(response => {
    projectOptions.value = response.rows.map(item => ({
      value: item.id,
      label: item.projectName
    }));
    loadingProjects.value = false;
  });
}

// 在组件挂载时获取项目列表
onMounted(() => {
  getProjectList();
});
// ... existing code ...




const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    appointmentTime: null,
  },
  rules: {
    appointmentTime: [
      { required: true, message: "预约时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询预约管理列表 */
function getList() {
  loading.value = true;
  listAppointment(queryParams.value).then(response => {
    appointmentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    appointmentTime: null,
    memberId: null,
    employeeId: null,
    estimatedProfit: null,
    startTime: null,
    endTime: null,
    status: null,
    notes: null,
    reminderTime: null,
    projectId: null
  };
  appointmentProjectList.value = [];
  proxy.resetForm("appointmentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加预约管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getAppointment(_id).then(response => {
    form.value = response.data;
    appointmentProjectList.value = response.data.appointmentProjectList;
    open.value = true;
    title.value = "修改预约管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["appointmentRef"].validate(valid => {
    if (valid) {
      form.value.appointmentProjectList = appointmentProjectList.value;
      if (form.value.id != null) {
        updateAppointment(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAppointment(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除预约管理编号为"' + _ids + '"的数据项？').then(function() {
    return delAppointment(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** ${subTable.functionName}序号 */
function rowAppointmentProjectIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** ${subTable.functionName}添加按钮操作 */
function handleAddAppointmentProject() {
  let obj = {};
  obj.projectId = "";
  appointmentProjectList.value.push(obj);
}

/** ${subTable.functionName}删除按钮操作 */
function handleDeleteAppointmentProject() {
  if (checkedAppointmentProject.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的${subTable.functionName}数据");
  } else {
    const appointmentProjects = appointmentProjectList.value;
    const checkedAppointmentProjects = checkedAppointmentProject.value;
    appointmentProjectList.value = appointmentProjects.filter(function(item) {
      return checkedAppointmentProjects.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleAppointmentProjectSelectionChange(selection) {
  checkedAppointmentProject.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('appointment/appointment/export', {
    ...queryParams.value
  }, `appointment_${new Date().getTime()}.xlsx`)
}

getList();
</script>
